package com.hexb.core.utils

import org.slf4j.Logger
import org.slf4j.LoggerFactory

import java.beans.PropertyDescriptor
import java.lang.reflect.Field

/**
 * @Package : com.hexb.core.utils
 * @Author : hexb 
 * @Date : 2018-08-17 11:28
 */
class ReflectionHelper {

    static Logger logger = LoggerFactory.getLogger(ReflectionHelper.class)

    //获取class可访问字段
    static List<Field> getClassFields(Class<?> clazz) {
        def fields = []
        if (clazz.superclass && clazz.superclass.name != 'java.lang.Object') {
            fields.addAll(getClassFields(clazz.superclass))
        }
        fields.addAll(clazz.getDeclaredFields().findAll {
            !it.synthetic && it.name != 'metaClass' && hasGetter(it, clazz) && hasSetter(it, clazz)
        })
        fields
    }

    static boolean hasGetter(Field f, Class<?> clazz) {
        try {
            PropertyDescriptor pd = new PropertyDescriptor(f.name, clazz)
            return pd.getReadMethod() != null
        } catch (e) {
            logger.debug("${clazz.name}.${f.name} no getter")
        }
        return false
    }

    static boolean hasSetter(Field f, Class<?> clazz) {
        try {
            PropertyDescriptor pd = new PropertyDescriptor(f.name, clazz)
            return pd.getWriteMethod() != null
        } catch (e) {
            logger.debug("${clazz.name}.${f.name} no setter")
        }
        return false
    }
}
